package com.acando.feide;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;

import com.acando.feide.jaxb.EnterpriseType;
import com.acando.feide.utils.AppException;
import com.martiansoftware.jsap.FlaggedOption;
import com.martiansoftware.jsap.JSAP;
import com.martiansoftware.jsap.JSAPException;
import com.martiansoftware.jsap.JSAPResult;
import com.martiansoftware.jsap.Switch;

public class Importer {

    /**
     * Main method for the Feide Integration import application.
     * 
     * @param args
     * @throws JSAPException
     */
    public static void main(String[] args) throws JSAPException {

        Package p = Importer.class.getPackage();
        System.out.println("Feide Importer ");
        if (p.getImplementationVersion() != null) {
            System.out.println("Version : " + p.getImplementationVersion());
        }

        // ---- Command line argument interpretation -----------

        JSAP jsap = new JSAP();

        FlaggedOption inDir = new FlaggedOption("inDir").setStringParser(JSAP.STRING_PARSER).setDefault("import-files")
                .setLongFlag("indir").setShortFlag('i');
        inDir.setHelp("Directory where to place input files ");

        FlaggedOption mainFile = new FlaggedOption("mainFile").setStringParser(JSAP.STRING_PARSER).setRequired(true)
                .setLongFlag("mainFile").setShortFlag('m');
        mainFile.setHelp("Main input file to use");

        FlaggedOption extraFile = new FlaggedOption("extraFile").setStringParser(JSAP.STRING_PARSER).setRequired(false)
                .setLongFlag("extraFile").setShortFlag('e');
        extraFile.setHelp("Extra input file to use");

        FlaggedOption xsltFile = new FlaggedOption("xslFile").setStringParser(JSAP.STRING_PARSER).setRequired(true)
                .setLongFlag("xslFile").setShortFlag('x');
        xsltFile.setHelp("XSLT transform file to use");

        Switch help = new Switch("help").setLongFlag("help").setShortFlag('?');
        help.setHelp("Prints this help message");

        jsap.registerParameter(inDir);
        jsap.registerParameter(xsltFile);
        jsap.registerParameter(mainFile);
        jsap.registerParameter(extraFile);
        jsap.registerParameter(help);
        JSAPResult config = jsap.parse(args);

        if (config.getBoolean("help")) {
            System.out.println();
            System.out.println("Usage: java -jar importer.jar ");
            System.out.println("                " + jsap.getUsage());
            System.out.println();
            System.out.println(jsap.getHelp());
            System.exit(0);
        }

        // check whether the command line was valid, and if it wasn't,
        // display usage information and exit.
        if (!config.success()) {

            for (Iterator<?> errs = config.getErrorMessageIterator(); errs.hasNext();) {
                System.err.println("Error: " + errs.next());
            }
            System.err.println();
            System.err.println("Usage: java -jar importer.jar ");
            System.err.println("                " + jsap.getUsage());
            System.err.println();
            System.err.println(jsap.getHelp());
            System.exit(1);
        }

        try {

            // ---------- XSLT Transform part ----------------

            Transformer transformer = new Transformer(new File(config.getString("inDir")),
                    config.getString("mainFile"), config.getString("extraFile"), new File(config.getString("xslFile")));
            transformer.transform();

            // ------ JAXB - import of feide file part ----------------------

            FeideFileReader feideFileReader = new FeideFileReader();
            EnterpriseType enterpriseType = null;
            enterpriseType = feideFileReader.doRead();

            // ------ Generate LDIF output part ----------------------------

            SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
            StringBuffer outFileName = new StringBuffer();
            outFileName.append(format.format(new Date()));
            if (enterpriseType.getProperties().getType().contains("full")) {
                outFileName.append("_full_import.ldif");
            } else {
                outFileName.append("_partiell_import.ldif");
            }
            LDIFGenerator generator = new LDIFGenerator();
            generator.generate(enterpriseType, new File(outFileName.toString()));

            // ------- Success message part ----------------------------------

            System.out.println("");
            System.out.println("LDIF file generation successful.");
            System.out.println("Result is file : " + outFileName.toString());
            System.out.println("");

        } catch (AppException ae) {

            // ------ Application generated error output ---------------------

            System.err.println("");
            System.err.println("An error occured during generation.");
            System.err.println("Error message : " + ae.getMessage());
            if (ae.getCause() != null) {
                System.err.println("Additional info : " + ae.getCause().getMessage());
            }

        } catch (Exception e) {

            // ------- Other error output -------------------------------------

            System.err.println("");
            System.err.println("An unknown error occured during generation.");
            System.err.println("Exception class : " + e.getClass().getCanonicalName());
            System.err.println("Error message and stacktrace : " + e.getMessage());
            e.printStackTrace();

        }
    }

}
